<?php
/**
 * @file Controller.class.php
 * @author 禅元天道 chanyuantiandao@126.com
 * @DateTime 2022-01-17 15:33
 * @brief 所有控制器的父类
 */

!defined('CHAN_CMS') && exit('非法访问！');

abstract class Controller
{
    protected $page_vars = array();
    protected $templateParser;

    public function __construct()
    {
        $this->templateParser = Template::getInstance();
    }

    function _before(){}

    function _after(){}

    function assign($key, $val){
        $this->page_vars['tpl_'.$key] = $val;
    }

    public function M($table){
        return new Model($table);
    }

    function display($tpl = ''){
        $controllerName = str_replace('controller', '', strtolower(get_called_class()));
        $actionName = debug_backtrace()[1]['function'];

        if(empty($tpl)){
            $tpl = $controllerName.'-'.$actionName;
        }else{
            $paths = explode(':', $tpl);
            if(sizeof($paths) == 1){
                $tpl = $controllerName.'-'.$paths[0];
            }else if(sizeof($paths) == 2){
                $tpl = $paths[0].'-'.$paths[1];
            }else{
                $tpl = $controllerName.'-'.$actionName;
            }
        }

        if(!empty($this->page_vars)){
            extract($this->page_vars, EXTR_SKIP);
        }

        $result = $this->templateParser->parseFile($tpl);
        if(!$result){
            throw new ChanException('解析模板文件'.$tpl.'失败!');
        }
        include($result);
    }

}